export class Events {
    constructor() {
        this._$event = {};

    }
    on(str, event, scope) {
        if (!this._$event.hasOwnProperty(str)) this._$event[str] = [];
        this._$event[str].push({ event, scope });
    }
    off(str, event) {
        if (str) {
            if (event) {
                let events = this._$event.hasOwnProperty(str) ? this._$event[str] : [];
                for (let i = 0; i < events.length; i++) {
                    const element = events[i];
                    if (element.event === event) {
                        events.splice(i, 1);
                        break;
                    }
                }
            } else {
                delete this._$event[str];
            }
        }
    }
    run(...params) {
        var str = params[0];
        let _arguments = [];
        for (let i = 0; i < params.length; i++) {
            const element = params[i];
            if (i >= 1) {
                _arguments.push(element);
            }
        }
        let events = this._$event.hasOwnProperty(str) ? this._$event[str] : [];
        events.forEach((element) => {
            element.event.apply(element.scope, _arguments);
        });
    }
}
class WebSocketSingle extends Events {

    constructor(serviceUrl, token) {
        super()

        this.serviceUrl = '';
        this.ws = ''
        this.status = '';
        this.pingPong = ''

        this.serviceUrl = serviceUrl;
        this.connect();
    }
    connect() {
        this.ws = new WebSocket(this.serviceUrl);
        this.ws.binaryType = "arraybuffer"
        this.ws.onopen = e => {
            this.status = 'open';
            this.getMessage();
            console.log('%cWebSocket:连接已打开', "color: blue");
            this.run('onOpen', 'WS_event_open');
        };
        this.ws.onclose = () => {
            console.log('%cWebSocket:连接已关闭', "color: blue");
        }
        this.ws.onerror = () => {
            console.log('%cWebSocket:链接出现问题', "color: red")
            this.run('onError', 'WS_event_error');
        }
    }
    getMessage() {
        this.ws && (this.ws.onmessage = event => {
            this.pingPong = 'pong';
            this.run('Message', event.data)
        });
    }
    close() {
        this.ws && this.ws.close();
    }
}


export default WebSocketSingle